package com.saibowisdom.storage.aspirator.common;


import com.saibowisdom.storage.aspirator.common.meta.FieldInfo;
import com.saibowisdom.storage.aspirator.common.meta.MonitorInfo;
import com.saibowisdom.storage.aspirator.common.meta.NodeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

public class MetaRetrieve implements Serializable {

    /**
     * 日志
     */
    static final Logger logger = LoggerFactory.getLogger(MetaRetrieve.class);

    public static ThreadLocal<DateFormats> dateFormatsT = new ThreadLocal<DateFormats>() {
        public DateFormats initialValue() {
            logger.info("实例化dateFormatsT");
            return new DateFormats();
        }
    };
    /**
     *
     */
    private static final long serialVersionUID = 3240372808698591361L;

    /**
     * 缓存表-字段关系
     */
    Map<String, Map<String, FieldInfo>> cache = new HashMap<>();
    /**
     * 表-重新查询时间缓存
     */
    Map<String, Integer> tableTTL = new HashMap<>();
    /**
     * 表名md5
     */
    Map<String, String> tableMD5 = new HashMap<>();
    /**
     * 缓存当前表的md5
     */
    Map<String, String> oldTableMD5 = new HashMap<>();
    /**
     * 表要修改的字段
     */
    Map<String, Map<String, Integer>> toCreateFields = new HashMap<>();


    private Calendar startDate = Calendar.getInstance();

    /**
     * 连接
     */
    Connection con = null;
    /**
     * jdbc连接
     */
    String jdbc = null;
    /**
     * 用户名
     */
    String user = null;
    /**
     * 密码
     */
    String passwd = null;

    /**
     * 获取字段和其属性
     *
     * @param table 表
     * @return Map
     */
    public Map<String, FieldInfo> getFieldTypes(String table) {

        Map<String, FieldInfo> fieldMap = cache.get(table);

        if (fieldMap == null) {
            getCache(table);
        }
        fieldMap = cache.get(table);
        if (fieldMap == null) {
            return null;
        }

        return fieldMap;
    }


    /**
     * 日期格式转换
     *
     * @param dt 日期字符串
     * @return dt
     */
    public String dateTrans(String dt) {
        /** 数字匹配 */
        final String regN = "^\\d+$";
        /** 英文和数字 */
        final String regNE = ".*\\p{Alpha}.*";
        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        final SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        //String date;
        final ArrayList<SimpleDateFormat> dateFormats;
        try {
            /** 时间戳格式 */
            if (dt.matches(regN)) {
                if (dt.length() == 10) {
                    dt = dt + "000";
                    dt = dateFormat.format(new Date(Long.parseLong(dt)));
                    //date = dt;
                } else if (dt.length() == 8) {
                    //yyyyMMdd格式日期转换为yyyyMMddHHmmss格式
                    dt = dt + "000000";
                    dt = dateFormat.format(dateFormat1.parse(dt));
                    //date = dt;
                } else if (dt.length() == 14) {
                    //yyyyMMddHHmmss格式
                    dt = dateFormat.format(dateFormat1.parse(dt));
                    //date = dt;
                } else if (dt.length() == 13) {
                    //yyyyMMddHHmmss格式
                    dt = dateFormat.format(new Date(Long.parseLong(dt)));
                    //date = dt;
                }
                return dt;
            } else if (dt.matches(regNE)) {

                if (dt.contains("+")) {
                    dt = dt.substring(0, dt.indexOf("+"));
                }

                //dateFormats = DateFormats.dateTimeDateFormatsEN;
                dateFormats = dateFormatsT.get().getDateTimeDateFormatsEN();

            } else {
                //28-04-2016
                if (dt.length() == 10) {
                    String[] dtarr = dt.split("-");
                    if (dtarr[dtarr.length - 1].length() == 4) {
                        dateFormats = dateFormatsT.get().getDateTimeDateFormatsEN();
                    } else {
                        dtarr = dt.split("/");
                        if (dtarr[dtarr.length - 1].length() == 4) {
                            dateFormats = dateFormatsT.get().getDateTimeDateFormatsEN();
                        }else{
                            dateFormats = dateFormatsT.get().getDateTimeDateFormatsCH();
                        }
                    }
                } else {
                    dateFormats = dateFormatsT.get().getDateTimeDateFormatsCH();
                }
                //dateFormats = DateFormats.dateTimeDateFormatsCH;
                //dateFormats = dateFormatsT.get().getDateTimeDateFormatsCH();
            }
            Date parseDate = null;
            for (SimpleDateFormat dformat : dateFormats) {
                boolean result = true;
                try {
                    parseDate = dformat.parse(dt);
                } catch (Exception e) {
                    result = false;
                    parseDate = null;
                }
                if (result) {
                    break;
                }
            }
            if (parseDate == null) {
                return null;
            }
            dt = dateFormat.format(parseDate);

        } catch (Exception e) {
            dt = null;
        }
        return dt;
    }


    public enum DataType {
        VARCHAR, INTEGER, BIGINT, FLOAT, DOUBLE, DATE, BLOB;

        public static DataType getType(String type) {
            return valueOf(type.toUpperCase());
        }
    }

    /**
     * 获取字段类型
     *
     * @param table  表名
     * @param source 来源
     * @param field  字段
     * @return dateType
     */
    public DataType getType(String table, String source, String field) {
        final Map<String, FieldInfo> fieldMap = cache.get(table);
        final FieldInfo fi = fieldMap.get(field);

        if (fi == null) {
            return null;
        }
        String type = fieldMap.get(field).getDataTypeString(source).toUpperCase();
        if (source.toLowerCase().equals("es")) {
            if (type.equals("STRING")) {
                type = "VARCHAR";
            }
            if (type.equals("LONG")) {
                type = "BIGINT";
            }
        }
        return DataType.getType(type);
    }


    /**
     * 设置数据源
     *
     * @param jdbc   jdbc地址
     * @param user   用户名
     * @param passwd 密码
     */
    public void setDataSource(String jdbc, String user, String passwd) {
        this.jdbc = jdbc;
        this.user = user;
        this.passwd = passwd;
    }

    /**
     * 获取连接
     *
     * @return Connection
     * @throws Exception 异常
     */
    private Connection getConn() throws Exception {

        /*try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        final String url = jdbc;
        final String username = user;
        final String password = passwd;
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException se) {
            con = null;
            throw new Exception("连接mysql失败");
        }*/

        return C3p0ConnectionPool.getInstance().getConnection();
    }

    /**
     * 释放连接
     *
     * @param con 连接对象
     */
    private void releaseConnection(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取主键list
     *
     * @param table 表
     * @return lst
     */
    public List<String> getPrikeyList(String table) {

        final List<String> lst = new ArrayList<>();

        Map<String, FieldInfo> fieldMap = cache.get(table);
        final String[] pkStr = new String[100];
        int pkMax = 0;
        if (fieldMap == null) {
            getCache(table);
            fieldMap = cache.get(table);
        }
        if (fieldMap == null) {
            return null;
        }

        for (Map.Entry<String, FieldInfo> entry : fieldMap.entrySet()) {
            if (entry.getValue().isPrimkey()) {

                /** 复合主键 */
                final int idx = entry.getValue().getCompositePrimkey();
                if (idx > 0 && idx < 100) {
                    if (pkMax < idx) {
                        pkMax = idx;
                    }

                    pkStr[idx] = entry.getValue().getField();

                }
            }
        }
        lst.addAll(Arrays.asList(pkStr).subList(1, pkMax + 1));
        return lst;
    }

    /**
     * 建表sql语句
     *
     * @param table 表名
     * @return string
     */
    public String getCreateSql(String table) {
        String sql = "create table if not exists ";
        sql += table;
        Map<String, FieldInfo> fieldMap = cache.get(table);
        final FieldInfo[] pkStr = new FieldInfo[100];
        if (fieldMap == null) {
            getCache(table);
            fieldMap = cache.get(table);
        }

        sql += " (";
        boolean begin = true;
        String fieldStr = "";
        int pkCount = 0;
        int pkMax = 0;
        for (Map.Entry<String, FieldInfo> entry : fieldMap.entrySet()) {

            if (entry.getValue().isPrimkey()) {

                /** 组合主键 */
                final int idx = entry.getValue().getCompositePrimkey();
                if (idx > 0 && idx < 100) {
                    if (pkStr[idx] != null) {
                        return null;
                    }
                    pkStr[idx] = entry.getValue();
                    pkCount++;
                    if (pkMax < idx) {
                        pkMax = idx;
                    }
                }
                if (getType(table, "hbase", entry.getKey()) != DataType.VARCHAR) {
                    continue;
                }
            }


            if (!begin) {
                fieldStr += ",";
            }
            fieldStr += entry.getValue().getField();
            fieldStr += " ";
            fieldStr += entry.getValue().getDataTypeString("hbase");
            begin = false;

        }

        assert (pkMax == pkCount);
        begin = true;
        if (pkCount > 0) {
            fieldStr += " CONSTRAINT PK PRIMARY KEY(";

            for (int ii = 1; ii <= pkMax; ii++) {
                if (!begin) {
                    fieldStr += ",";
                    sql += ",";
                }
                if (getType(table, "hbase", pkStr[ii].getField()) == DataType.VARCHAR) {
                    sql += pkStr[ii].getField() + "_";
                    fieldStr += pkStr[ii].getField() + "_";
                } else {
                    sql += pkStr[ii].getField();
                    fieldStr += pkStr[ii].getField();
                }
                sql += " ";
                sql += pkStr[ii].getDataTypeString("hbase");

                sql += " NOT NULL";

                begin = false;
            }
            fieldStr += ")";
        } else {
            return null;
        }
        sql += ",";
        sql += fieldStr;
        sql += ")";

        return sql;
    }

    public boolean getCache(String table) {
        return getCache(table, false);
    }

    /**
     * 查表并缓存
     *
     * @param table  表名
     * @param reload 重新查数据库
     * @return boolean
     */
    @SuppressWarnings("unchecked")
    public boolean getCache(String table, boolean reload) {

        String str = "select t.table_name,f.field_name, f.data_type,f.primkeyed,f.composite_primkeyed,f.indexed,f.stored,f.dcoument_values," +
                "f.mul_values,f.partition_type from table_def as t join field_def as f on t.table_id=f.table_id ";


        /** 指定table查询，没指定则查全部 */
        if (table.length() > 1) {
            str += "where t.table_name='" +
                    table + "'";
            if (!reload) {
                final Map<String, FieldInfo> fieldMap = cache.get(table);
                if (fieldMap != null) {
                    return true;
                }

            }
        }

        boolean flag = true;
        ResultSet rs = null;
        Connection con = null;
        try {
            con = getConn();
            if (con == null) {
                //logger.error("查询表 {} ,创建mysql连接失败", table);
                return false;
            }
            final Statement stmt = con.createStatement();
            rs = stmt.executeQuery(str);

            // 获取列数
            final ResultSetMetaData metaData = rs.getMetaData();

            // 遍历ResultSet中的每条数据
            while (rs.next()) {

                final String tableName = rs.getString(metaData.getColumnLabel(1));

                Map<String, FieldInfo> fieldMap = cache.get(tableName);
                if (fieldMap == null) {
                    fieldMap = new HashMap<>();
                    cache.put(tableName, fieldMap);
                }

                final FieldInfo info = new FieldInfo();
                final String fieldName = rs.getString(metaData.getColumnLabel(2));
                info.setTable(tableName);
                info.setField(fieldName);
                info.setDataType(rs.getInt(metaData.getColumnLabel(3)));
                info.setPrimkey(rs.getBoolean(metaData.getColumnLabel(4)));
                info.setCompositePrimkey(rs.getInt(metaData
                        .getColumnLabel(5)));
                info.setIndexed(rs.getInt(metaData.getColumnLabel(6)));
                info.setStored(rs.getBoolean(metaData.getColumnLabel(7)));
                info.setDocValues(rs.getBoolean(metaData.getColumnLabel(8)));
                info.setMulValues(rs.getBoolean(metaData.getColumnLabel(9)));
                info.setPartitionType(rs.getInt(metaData.getColumnLabel(10)));

                info.setCleanHtml(false);
                Map<String, Integer> toCreateMap = toCreateFields.get(tableName);
                if (null == toCreateMap) {
                    toCreateMap = new HashMap<>();
                    toCreateFields.put(tableName, toCreateMap);
                }
                if (null == fieldMap.get(fieldName)) {
                    toCreateMap.put(fieldName, 1);
                }


                fieldMap.put(fieldName, info);
            }

            if (table.length() > 1) {
                final String md5 = tableMD5.get(table);
                if (md5 != null) {
                    oldTableMD5.put(table, md5);
                }

                tableMD5.put(table, String.valueOf(cache.get(table).hashCode()));

                tableTTL.put(table, 1000);
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            //logger.error("查询表 {} 时出错,错误为 {} ", table, e1.getMessage());
            e1.printStackTrace();
            flag = false;
        }

        // 关闭记录集
        try {
            if (rs != null) {
                rs.close();
            }
            releaseConnection(con);
        } catch (SQLException e) {
            //logger.error("关闭连接时出错,错误为 {} ", table, e.getMessage());
            //e.printStackTrace();
        }
        return flag;
    }

    /**
     * 检测表结构
     *
     * @param table 表名
     * @param map2  内容
     * @return boolean
     */
    public boolean checkSchema(String table, Map<String, Object> map2) {
        /** 每隔1000次，查询mysql一次 */
        Integer ttl = tableTTL.get(table);
        final Calendar now = Calendar.getInstance();
        //startDate.add(Calendar.SECOND, 10);
        //System.out.println("dddd: " + (now.getTimeInMillis() - startDate.getTimeInMillis()) / 1000);
        if (ttl == null || ttl < 1 || (now.getTimeInMillis() - startDate.getTimeInMillis()) / 1000 / 60 >= 2) {
            logger.info("查询数据库,确定表结构");
            getCache(table, true);
            ttl = 1000;
            startDate = now;
        } else {
            if (map2 != null) {
                final Map<String, FieldInfo> fieldMap = cache.get(table);
                if (fieldMap != null) {
                    for (Map.Entry<String, Object> entry : map2.entrySet()) {
                        /** 数据中有新字段 认为数据变了表也会变*/
                        if (fieldMap.get(entry.getKey()) == null) {
                            getCache(table, true);
                            ttl = 1000;
                            startDate = now;
                            break;
                        }
                    }
                }
            }
        }

        ttl--;
        tableTTL.put(table, ttl);
        final String md5 = tableMD5.get(table);

        final String oldMd5 = oldTableMD5.get(table);

        if (oldMd5 == null) {
            return false;
        }

        final boolean check = md5.equals(oldMd5);

        if (check) {
            return false;
        } else {
            oldTableMD5.put(table, md5);
            return true;
        }

    }

    /**
     * 获取修改的field
     *
     * @param table 表名
     * @return list
     */
    public List<String> getAlterField(String table) {
        final Map<String, Integer> toCreateMap = toCreateFields.get(table);
        if (null == toCreateMap) {
            return null;
        }

        final List<String> newFields = new ArrayList<>();

        for (Map.Entry<String, Integer> entry : toCreateMap.entrySet()) {
            if (entry.getValue() == 1) {
                newFields.add(entry.getKey());
            }
        }
        toCreateMap.clear();
        return newFields;

    }


    /**
     * 更新节点状态
     *
     * @param nodeInfo 节点状态
     * @throws Exception 异常
     */
    public void updateNodeState(NodeInfo nodeInfo) throws Exception {
        final Connection connection = getConn();
        final String updateSql = "update storage_node set state = " + nodeInfo.isState() + ",stop=" + nodeInfo.isStop() +
                " where ip = '" + nodeInfo.getIp() + "' and host = '" + nodeInfo.getHost() + "' AND type = " + nodeInfo.getType();
        final Statement statement;
        statement = connection.createStatement();
        final int up = statement.executeUpdate(updateSql);
        if (up < 1) {
            final String insertSql = "insert into storage_node (ip,host,state,updatetime,stop,type) values('" + nodeInfo.getIp() + "','" +
                    nodeInfo.getHost() + "'," + nodeInfo.isState() + "," + new Date().getTime() + "," + nodeInfo.isStop() + "," + nodeInfo.getType() + ")";
            statement.executeUpdate(insertSql);
        }
        releaseConnection(connection);
        statement.close();
    }


    /**
     * 更新节点时间
     *
     * @param nodeInfo 节点
     * @throws Exception 异常
     */
    public void updateNodeTime(NodeInfo nodeInfo) throws Exception {
        final Connection connection = getConn();
        final String updateSql = "update storage_node set updatetime = " + new Date().getTime() +
                " where ip = '" + nodeInfo.getIp() + "' and host = '" + nodeInfo.getHost() + "' AND type = " + nodeInfo.getType();
        final Statement statement;
        statement = connection.createStatement();
        statement.executeUpdate(updateSql);
        releaseConnection(connection);
        statement.close();
    }

    /**
     * 更新节点数量
     *
     * @param nodeInfo 节点
     * @throws Exception 异常
     */
    public void updateNodeProcessNum(NodeInfo nodeInfo) throws Exception {
        final Connection connection = getConn();
        final String updateSql = "update storage_node set scount = " + nodeInfo.getScount() + ",fcount=" + nodeInfo.getFcount() + ",icount=" + nodeInfo.getIcount() +
                " where ip = '" + nodeInfo.getIp() + "' and host = '" + nodeInfo.getHost() + "' AND  type = " + nodeInfo.getType();
        final Statement statement;
        statement = connection.createStatement();
        statement.executeUpdate(updateSql);
        releaseConnection(connection);
        statement.close();
    }

    /**
     * 生成monitorInfo并插入数据库
     *
     * @param ip      ip
     * @param host    host
     * @param content 发生错误的内容
     * @param error   错误信息
     * @param etype   错误类型
     * @param source  错误来源
     * @throws Exception 异常
     */
    public void insertErrorInfo(String ip, String host, String content, String error, int etype, int source) throws Exception {
        final MonitorInfo monitorInfo = new MonitorInfo();
        monitorInfo.setContent(content);
        monitorInfo.setError(error);
        monitorInfo.setHost(host);
        monitorInfo.setIp(ip);
        monitorInfo.setType(etype);
        monitorInfo.setSource(source);
        insertErrorInfo(monitorInfo);
    }

    /**
     * 插入错误信息
     *
     * @param monitorInfo 错误信息
     * @throws Exception 异常
     */
    public void insertErrorInfo(MonitorInfo monitorInfo) throws Exception {
        final Connection connection = getConn();
        final String insertSql = "insert into storage_monitoring1 (ip,host,content,error,etype,updatetime,source) values('" + monitorInfo.getIp() + "','" +
                monitorInfo.getHost() + "','" + monitorInfo.getContent() + "','" + monitorInfo.getError() +
                "'," + monitorInfo.getType() + ",Now()," + monitorInfo.getSource() + ")";
        final Statement statement;
        statement = connection.createStatement();
        statement.executeUpdate(insertSql);
        releaseConnection(connection);
        statement.close();
    }


    /**
     * 插入错误信息
     *
     * @param key       主键
     * @param errorDate 错误日期
     * @throws Exception
     */
    public void insertErrorData(String key, String errorDate) throws Exception {
        final Connection connection = getConn();
        final String insertSql = "insert into error_data (pkey,errordate,date) values('" + key + "','" +
                errorDate + "',Now())";

        final Statement statement;
        statement = connection.createStatement();
        statement.executeUpdate(insertSql);
        releaseConnection(connection);
        statement.close();
    }


    /**
     * 插入错误信息
     *
     * @param monitorInfo 错误信息
     * @throws Exception 异常
     */
    public void updateErrorInfo(MonitorInfo monitorInfo) throws Exception {
        final Connection connection = getConn();
        int type = monitorInfo.getType();
        if (type == 2) {
            if (monitorInfo.getCount() >= 10) {
                type = 3;
            }
        }
        final String insertSql = "UPDATE storage_monitoring1 SET count = " + monitorInfo.getCount() + ",etype = " + type + " WHERE id = " + monitorInfo.getId();
        final Statement statement;
        statement = connection.createStatement();
        statement.executeUpdate(insertSql);
        releaseConnection(connection);
        statement.close();
    }

    /**
     * 查询要重新插入的错误信息
     *
     * @param nodeInfo nodeInfo
     * @throws Exception 异常
     */
    public ArrayList<MonitorInfo> getErrorInfo(NodeInfo nodeInfo) throws Exception {
        final Connection connection = getConn();
        final String insertSql = "SELECT  * from storage_monitoring1 WHERE etype = 2 AND ip = '" + nodeInfo.getIp() + "' AND host = '" + nodeInfo.getHost() + "' AND " +
                "source = " + nodeInfo.getType() + " limit 1000";
        final Statement statement;
        final ArrayList<MonitorInfo> monitorInfos = new ArrayList<>();
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery(insertSql);
        while (resultSet.next()) {
            final MonitorInfo monitorInfo = new MonitorInfo();
            monitorInfo.setContent(resultSet.getString("content"));
            monitorInfo.setId(resultSet.getInt("id"));
            monitorInfo.setCount(resultSet.getInt("count"));
            monitorInfo.setIp(resultSet.getString("ip"));
            monitorInfo.setHost(resultSet.getString("host"));
            monitorInfo.setType(resultSet.getInt("etype"));
            monitorInfos.add(monitorInfo);
        }
        releaseConnection(connection);
        statement.close();

        return monitorInfos;
    }

    public static void main(String[] args) {
        /*MetaRetrieve metaRetrieve = new MetaRetrieve();
        metaRetrieve.setDataSource("jdbc:mysql://192.168.1.221:3306/internetdb?useUnicode=true&amp;characterEncoding=utf8", "root", "123!@#");
        String ip = "192.168.1.108";
        String host = "lll";
        String content = "{\"DATA\":[{\"content\":\"2015年全市服务质量满意度指数80.64 南通市质监局委托<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>南通<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em>和南通市质量协会联合对养老、邮电、电商、文体、铁路、旅游六大服务行业进行的顾客满意度调查，满意度指数为80.64。其中，生产性服务业顾客满意度为80.75，生活性服务业满意度为80.54，总体满意度为“满意”。\",\"createdate\":\"1443418580000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/1472807544/CCCqNlzm7\",\"user_headimg\":\"http://tp1.sinaimg.cn/1472807544/50/5725018796/1\",\"user_nickname\":\"湾洪微波\",\"user_url\":\"http://weibo.com/u/1472807544\"},{\"content\":\"<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>下设15个直属事业单位：机关服务<em class=\\\"red\\\">中心</em>、<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em>、国际检验检疫标准与技术法规研究中心、纤维检验局、检验检疫科学研究院、标准化研究院、计量科学研究院、质量认证中心、合格评定<em class=\\\"red\\\">国家</em>认可中心、特种设备检测研究中心，人力资源开发培训中心、质量报社、国门时报社、标准出版社和计量出版社\",\"createdate\":\"1432627512000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/2191753095/CjCZ9nsRb\",\"user_headimg\":\"http://tp4.sinaimg.cn/2191753095/50/5725854898/1\",\"user_nickname\":\"质量缔造能量\",\"user_url\":\"http://weibo.com/dizaonengliang\"},{\"content\":\"//<a href=\\\"http://weibo.com/n/%E9%80%9F%E8%85%BE%E4%B8%9A%E4%BD%99%E6%A3%80%E8%BD%A6%E5%91%98\\\" disable_usercard=\\\"name=速腾业余检车员\\\" suda-data=\\\"key=tblog_search_weibo&value=weibo_feed_at\\\" target=\\\"_blank\\\" class=W_linkb>@速腾业余检车员</a>:又是一个体制内的玩笑，就像速腾断轴事件中的国家质检总局的<em class=\\\"red\\\">国家质检总局信息中心</em>办公室主任<a href=\\\"http://weibo.com/n/%E8%B4%A8%E6%A3%80%E5%91%A8%E6%96%B0\\\" disable_usercard=\\\"name=质检周新\\\" suda-data=\\\"key=tblog_search_weibo&value=weibo_feed_at\\\" target=\\\"_blank\\\" class=W_linkb>@质检周新</a>\",\"createdate\":\"1431568170000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/5068471338/ChLoHc5JX\",\"user_headimg\":\"http://tp3.sinaimg.cn/5068471338/50/5737964573/1\",\"user_nickname\":\"美洁橱柜-小潘\",\"user_url\":\"http://weibo.com/u/5068471338\"},{\"content\":\"【认监委<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em>会同相关机构到<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>电子商务风险<em class=\\\"red\\\">中心</em>开展交流工作2015年4月21日，认监委<em class=\\\"red\\\">信息</em>中心会同相关机构到<em class=\\\"red\\\">总局</em>电商风险监测中心就促进电商企业健康发展，推行“良好电子商务规范”进行了深入交流。双方就共同推进良好电商认证工作以及共享电商监管信息达成初步意向。\",\"createdate\":\"1429626770000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/5334799960/Celz76GbC\",\"user_headimg\":\"http://tp1.sinaimg.cn/5334799960/50/5708667094/1\",\"user_nickname\":\"中认阳光\",\"user_url\":\"http://weibo.com/cncaic\"},{\"content\":\"从安徽省质监局获悉，近日，<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em><em class=\\\"red\\\">信息</em>办领导一行到安徽省质监局调研“金质工程”一期试点准备情况，并对省<em class=\\\"red\\\">质检</em><em class=\\\"red\\\">中心</em><em class=\\\"red\\\">信息</em>化建设基本情况进行了全面了解。省局计量处、食品处、特设处、信息<em class=\\\"red\\\">中心</em>的相关人员参加了座谈会。 <a title=\\\"\\\" href=\\\"http://t.cn/RA9h4Yk\\\" target=\\\"_blank\\\" mt=\\\"url\\\" action-type=\\\"feed_list_url\\\" suda-data=\\\"key=tblog_search_weibo&value=weibo_nologin_url\\\" class=\\\"W_linkb\\\">http://t.cn/RA9h4Yk</a> \",\"createdate\":\"1429055665000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/5415873361/CdlfAeUoE\",\"user_headimg\":\"http://tp2.sinaimg.cn/5415873361/50/40076042616/0\",\"user_nickname\":\"人社局_86752\",\"user_url\":\"http://weibo.com/u/5415873361\"},{\"content\":\"中国国家质检总局与东盟秘书处联合召开新闻发布会。中国国家质检总局局长支树平。中国国家质检总局称，将对此事继续给予关注。(完)。中国国家质检总局公布的检查结果。是“由于中国<em class=\\\"red\\\">国家质检总局信息中心</em>持有数据库之拥有权， <a title=\\\"\\\" href=\\\"http://t.cn/RAiTkri\\\" target=\\\"_blank\\\" mt=\\\"url\\\" action-type=\\\"feed_list_url\\\" suda-data=\\\"key=tblog_search_weibo&value=weibo_nologin_url\\\" class=\\\"W_linkb\\\">http://t.cn/RAiTkri</a> \",\"createdate\":\"1428552526000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/5415873361/CcslQncsH\",\"user_headimg\":\"http://tp2.sinaimg.cn/5415873361/50/40076042616/0\",\"user_nickname\":\"人社局_86752\",\"user_url\":\"http://weibo.com/u/5415873361\"},{\"content\":\"【南通市民对六大行业服务质量总体满意——服务求更好 有待再改进23日，南通质监局发布2014年全市服务质量满意度调查结果。本次调查，主要针对供电、银行、电信、医疗、出租车、物业等六个服务行业，由南通质监局委托<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>南通<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em>和市质量协会联合组织实施。<a title=\\\"http://www.zgnt.net/content/2014-10/27/content_2350552.htm\\\" href=\\\"http://t.cn/R7Xx1Nw\\\" target=\\\"_blank\\\" mt=\\\"url\\\" action-type=\\\"feed_list_url\\\" suda-data=\\\"key=tblog_search_weibo&value=weibo_nologin_url\\\" class=\\\"W_linkb\\\">http://t.cn/R7Xx1Nw</a>\",\"createdate\":\"1414372397000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/1708099187/BtszvesII\",\"user_headimg\":\"http://tp4.sinaimg.cn/1708099187/50/1294886037/0\",\"user_nickname\":\"南通网\",\"user_url\":\"http://weibo.com/zgnt\"},{\"content\":\"发表了博文《农夫山泉哪只一点甜!》你们看：“农夫山泉”在国内享有很高的认知度，2003年9月农夫山泉天然水被<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>评为“中国名牌”产品。你们再看：中华商业<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em>市场监测报告显示，从1999年至<a class=\\\"W_btn_c6\\\" target=\\\"_blank\\\" href=\\\"http://t.cn/RPqCrkP\\\" ><span class=\\\"W_btn_tag\\\"><em class=\\\"W_btn_icon\\\"><i class=\\\"icon_cd_link W_ico12\\\"></i><i class=\\\"W_vline S_line1_c\\\">|</i></em><em class=\\\"W_autocut W_linkb\\\">农夫山泉哪...</em></span></a>\",\"createdate\":\"1406356545000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/5104177679/BflWddb8n\",\"user_headimg\":\"http://tp4.sinaimg.cn/5104177679/50/0/1\",\"user_nickname\":\"用户5104177679\",\"user_url\":\"http://weibo.com/u/5104177679\"},{\"content\":\"发表了博文 《农夫山泉哪只一点甜！！！》 - 你们看：“农夫山泉”在国内享有很高的认知度， 2003年9月农夫山泉天然水被<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>评为“中国名牌”产品。 你们再看：中华商业<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em>市场监测报告 <a class=\\\"W_btn_c6\\\" target=\\\"_blank\\\" href=\\\"http://t.cn/Rvr4zgj\\\" ><span class=\\\"W_btn_tag\\\"><em class=\\\"W_btn_icon\\\"><i class=\\\"icon_cd_link W_ico12\\\"></i><i class=\\\"W_vline S_line1_c\\\">|</i></em><em class=\\\"W_autocut W_linkb\\\">农夫山泉哪...</em></span></a>\",\"createdate\":\"1404531587000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/5019536997/Bc8OmibzG\",\"user_headimg\":\"http://tp2.sinaimg.cn/5019536997/50/5744196059/0\",\"user_nickname\":\"JUST-SYMN\",\"user_url\":\"http://weibo.com/u/5019536997\"},{\"content\":\"发表了博文 《饲料生产厂家不得对标签有任何“遮遮掩掩”》 - 　　由<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>和<em class=\\\"red\\\">国家</em>标准委新修订发布的《饲料标签》(GB10648-2013)将于2014年7月1日起正式实施。记者从市标准化<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em> <a class=\\\"W_btn_c6\\\" target=\\\"_blank\\\" href=\\\"http://t.cn/RvQzLqt\\\" ><span class=\\\"W_btn_tag\\\"><em class=\\\"W_btn_icon\\\"><i class=\\\"icon_cd_link W_ico12\\\"></i><i class=\\\"W_vline S_line1_c\\\">|</i></em><em class=\\\"W_autocut W_linkb\\\">饲料生产厂...</em></span></a>\",\"createdate\":\"1403751053000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/5178376143/BaLE36Heg\",\"user_headimg\":\"http://tp4.sinaimg.cn/5178376143/50/0/1\",\"user_nickname\":\"德帅才\",\"user_url\":\"http://weibo.com/u/5178376143\"},{\"content\":\"<a class=\\\"a_topic W_linkb\\\" href=\\\"http://huati.weibo.com/k/%E6%BB%A8%E5%9F%8E%E5%A4%9C%E6%96%B0%E9%97%BB?from=526\\\"suda-data=\\\"key=tblog_search_weibo&value=weibo_nologin_topic\\\" target=\\\"_blank\\\">#滨城夜新闻#</a> 由<em class=\\\"red\\\">国家</em><em class=\\\"red\\\">质检</em><em class=\\\"red\\\">总局</em>和<em class=\\\"red\\\">国家</em>标准委新修订发布的《饲料标签》(GB10648-2013)将于2014年7月1日起正式实施。从市标准化<em class=\\\"red\\\">信息</em><em class=\\\"red\\\">中心</em>获悉，此次修订涉及商品饲料、饲料添加剂和饲料原料，如乳清粉、鱼粉、宠物食品等，企业均须修改现有标签，使标示内容符合新标准要求。\",\"createdate\":\"1403612043000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/3256103747/BawtDvmte\",\"user_headimg\":\"http://tp4.sinaimg.cn/3256103747/50/5665193502/0\",\"user_nickname\":\"新浪大连城市频道\",\"user_url\":\"http://weibo.com/XLDLCITY\"},{\"content\":\"支树平考察中国（上海）自由贸易试验区:支树平考察上海质检工作时要求 探索制度性创新 服务自贸区发展 2014-06-10 <em class=\\\"red\\\">国家质检总局信息中心</em> 6月9日，质检总局局长、党组书记支树平先后考察了中 ...(发自<a href=\\\"http://weibo.com/n/%E5%BE%AE%E5%8D%9A%E6%A1%8C%E9%9D%A2\\\" disable_usercard=\\\"name=微博桌面\\\" suda-data=\\\"key=tblog_search_weibo&value=weibo_feed_at\\\" target=\\\"_blank\\\" class=W_linkb>@微博桌面</a> <a title=\\\"http://desktop.weibo.com/?source=changweibo\\\" href=\\\"http://t.cn/zjj9IWH\\\" target=\\\"_blank\\\" mt=\\\"url\\\" action-type=\\\"feed_list_url\\\" suda-data=\\\"key=tblog_search_weibo&value=weibo_nologin_url\\\" class=\\\"W_linkb\\\">http://t.cn/zjj9IWH</a>）\",\"createdate\":\"1402371910000\",\"domain\":\"s.weibo.com\",\"url\":\"http://weibo.com/1870275990/B8la8dKNU\",\"user_headimg\":\"http://tp3.sinaimg.cn/1870275990/50/5725258960/1\",\"user_nickname\":\"网络上海\",\"user_url\":\"http://weibo.com/345201400\"}],\"TABLE\":\"original_data\"}";
        String error = "插入HBASE或ES original_data 失败,错误信息 upsert original_data (url_ varchar NOT NULL,content varchar,user_headimg varchar,title varchar,createdate date,domain varchar,image varchar,user_nickname varchar,propertys varchar,user_url varchar,parent_url varchar,url varchar,clientname varchar CONSTRAINT PK PRIMARY KEY(url_)) Connection refused ";
        try {
            metaRetrieve.insertErrorInfo(ip, host, content, error, 1, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        MetaRetrieve metaRetrieve = new MetaRetrieve();
        metaRetrieve.setDataSource("jdbc:mysql://192.168.1.221:3306/internetdb?useUnicode=true&amp;characterEncoding=utf8", "root", "123!@#");
        while (true) {
            try {
                Thread.sleep(1000 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(metaRetrieve.checkSchema("ttt2", null));

        }
    }
}
